package com.fh.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.fh.admin.entity.UmsAdmin;
import com.fh.admin.service.IUmsAdminService;
import com.fh.login.token.TokenCommons;
import com.fh.permission.service.IUmsPermissionService;
import com.fh.role.service.IUmsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@EnableWebSecurity  //让这个配置文件生效
@EnableGlobalMethodSecurity(prePostEnabled=true) //让权限校验的注解生效
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private IUmsAdminService adminService;
    @Autowired
    private IUmsPermissionService permissionService;
    @Autowired
    private IUmsRoleService roleService;


    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * always：保存session状态（每次会话都保存，可能会导致内存溢出
     * <p>
     * never：不会创建HttpSession，但是会使用已经存在的HttpSession
     * <p>
     * if_required：仅在需要HttpSession创建
     * <p>
     * stateless：不会保存session状态
     * ————————————————
     *
     * @param http
     * @throws Exception
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers( "/login/**","/upload/**","/Path/**").permitAll() //放过请求不用拦截
                .anyRequest().authenticated();//其他请求都要被拦截需要登陆认证;
        http.csrf().disable();//关闭csrf拦截
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.headers().cacheControl();

        //自定义过滤器处理token
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //档登陆认证失败是或没有权限访问时要返回自定义json数据
        http.exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
      }

    /**
     * 从数据库查询用户拥有的角色和权限
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    /**
     * 连接数据库查询用户和权限信息
     * @return
     */
    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        return username->{
            String userKey= TokenCommons.userKey(username,"user");
            String roleKey= TokenCommons.userKey(username,"role");
            String permissionKey= TokenCommons.userKey(username,"permission");
            UmsAdmin umsAdmin = null;
            if (redisTemplate.hasKey(userKey)){


                String adminJson = redisTemplate.opsForValue().get(userKey).toString();
                umsAdmin = JSON.parseObject(adminJson, UmsAdmin.class);

            }else {
                umsAdmin=adminService.getUserByUsername(username);
                redisTemplate.opsForValue().set(userKey, JSON.toJSONString(umsAdmin),TokenCommons.exp_time, TimeUnit.MINUTES);

            }

            if (umsAdmin!=null){
                Long userId = umsAdmin.getId();
                List<String>roleList=new ArrayList<>();
                if (redisTemplate.hasKey(roleKey)){
                    roleList= (List<String>) redisTemplate.opsForValue().get(roleKey);
                }else {
                    roleList= roleService.getRoleByUserId(userId);
                    redisTemplate.opsForValue().set(roleKey,roleList,TokenCommons.exp_time, TimeUnit.MINUTES);
                }
                List<String>permissionList= new ArrayList<>();
                if (redisTemplate.hasKey(permissionKey)){
                    permissionList= (List<String>) redisTemplate.opsForValue().get(permissionKey);
                }else {
                    permissionList= permissionService.getPermissionByUserId(userId);
                    redisTemplate.opsForValue().set(permissionKey,permissionList,TokenCommons.exp_time, TimeUnit.MINUTES);
                }
                return new AdminUserDetails(permissionList,roleList,umsAdmin);
            }else {
                throw new UsernameNotFoundException("用户不存在");
            }

        };

    }




    /**
     * 声明密码加密方式
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //认证管理器·
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
